﻿using System.Net.NetworkInformation;
using System.Net;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System;

namespace MqttService.Code
{
    public class IpHelper
    {
        public static bool PortInUse(int port)
        {
            bool inUse = false;

            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();

            foreach (IPEndPoint endPoint in ipEndPoints)
            {
                if (endPoint.Port == port)
                {
                    inUse = true;
                    break;
                }
            } 
            return inUse;  // 返回true说明端口被占用

        }
        /// <summary>
        /// 根据端口号获取进程Id
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public static int getProcessId(int port)
        {
            int processId = 0;
            Process pro = new Process();
            //设置命令行、参数
            pro.StartInfo.FileName = "cmd.exe";
            pro.StartInfo.UseShellExecute = false;
            pro.StartInfo.RedirectStandardInput = true;
            pro.StartInfo.RedirectStandardOutput = true;
            pro.StartInfo.RedirectStandardError = true;
            pro.StartInfo.CreateNoWindow = true;

            //启动CMD
            pro.Start();
            pro.StandardInput.WriteLine("netstat -ano");
            pro.StandardInput.WriteLine("exit");

            //获取结果
            Regex reg = new Regex(@"\s ",RegexOptions.Compiled);
            string line= null;
            while ((line = pro.StandardOutput.ReadLine()) != null)
            { 
                line = line.Trim();
                if (line.StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
                {
                    line = reg.Replace(line, ",");

                    string[] arr = line.Split("",' ');
                    //if (arr[1].EndsWith(":" + port))
                    //{
                    //    killProcess(Int32.Parse(arr[4]));
                    //}

                    processId = Int32.Parse(arr[4]);
                }
            }
            return processId;
        }
        /// <summary>
        /// 根据进程ID 杀死进程
        /// </summary>
        /// <param name="processId"></param>
        /// <returns></returns>
        public static bool killProcess(int processId)
        {
            bool flag = false;

            try
            {
                Process thisproc = Process.GetProcessById(processId);
                if (!thisproc.CloseMainWindow())//尝试关闭进程 释放资源
                { 
                    thisproc.Kill();//强制关闭
                }
                flag = true;
            }
            catch (Exception)
            {
                 
            }
            finally { 
                
            }
            return flag;
        }

    }
}
